package com.jams.goodox.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jams.goodox.R;
import com.jams.goodox.utils.DelayUtils;
import com.jams.goodox.utils.DensityUtil;

import java.util.HashMap;

public class SortWidget {
	private Context c;
	private RelativeLayout sort_view_parent;
	private TextView show_first_pin;
	private static SortWidget toolbar;
	private ListView list;
	HashMap<String, Integer> alphaIndexer;
	private SortWidget(Context context){
		c = context;
		sort_view_parent = (RelativeLayout) ((Activity) context).findViewById(R.id.sort_view_parent);
		show_first_pin = (TextView) ((Activity) context).findViewById(R.id.show_first_pin);
	}


	public static synchronized SortWidget create(Context view) {
		toolbar = new SortWidget(view);
		return toolbar;
	}

	public void setIndexes(Object[] b1,ListView list,HashMap<String, Integer> alphaIndexer) {
		this.list = list;
		this.alphaIndexer = alphaIndexer;
		SortView view = new SortView(c, b1);
		view.setBackgroundColor(Color.TRANSPARENT);
		RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(-1, DensityUtil.dp2px(c, 19.0f * b1.length)+15);
		rlp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		sort_view_parent.addView(view, rlp);
		view.setOnTouchingLetterChangedListener(new LetterListViewListener());
	}


	/**
	 *
	 * @author Cosmo Jiang
	 * @email ruchao.jiang@uama.com.cn
	 * @date 2014年9月24日 下午5:00:29
	 * @desc
	 *
	 */
	private class LetterListViewListener implements
			SortView.OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			show_first_pin.setText(s);
			show_first_pin.setVisibility(View.VISIBLE);

			if (alphaIndexer != null && alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				// 将Listview的显示移到被选中首字母那行
				list.setSelection(position);
				// 延迟一秒后执行，让overlay为不可见

			}else{
				list.setSelection(0);
			}
			DelayUtils.doAfterDelay(1000, new DelayUtils.DelayDoListener() {
				@Override
				public void doAction() {
					show_first_pin.setVisibility(View.GONE);
				}
			});
		}
	}

}
